<template>
    <ul class="list">
        <!-- <li class="item" 
        v-for="(item,key) of cities" 
        :key="key"
        @click="handleLetterClick"
        @handleTouchMove='handleTouchMove'
        @touchstart="handleTouchStart"
        @handleTouchEnd="handleTouchEnd"
        >{{key}}</li> -->
        <li class="item" 
        v-for="item of letters" 
        :key="item"
        :ref="item"
        @click="handleLetterClick"
        @touchmove='handleTouchMove'
        @touchstart.prevent="handleTouchStart"
        @touchend="handleTouchEnd"
        >{{item}}</li>
        <!-- prevent事件修饰符 解决手机上按住划拉默认事件 -->
    </ul>
</template>
<script>
export default {
    name:'CityAlphabet',
    props:{
        cities:Object
    },
    data () {
        return {
            touchStatus:false,
            // 性能优化
            startY: 0,
            // 数据截留
            timer:null
        }
    },
    // 生命周期钩子
    updated() {
        this.startY =this.$refs['A'][0].offsetTop
    },
    computed:{
        letters (){
            const letters=[]
            for(let i in this.cities){
                letters.push(i)
            }
            return letters
        }
    },
    methods:{
        handleLetterClick (e) {
            // 获取被点击标签的文本值
            // console.log(e.target.innerText)
            // 兄弟组件传值 Alphabet -->City -->List

            // 事件触发给父组件City,父组件再通过属性的形式传给List组件
            this.$emit('change',e.target.innerText);
        },
        handleTouchStart () {
            this.touchStatus =true
        },
        handleTouchMove (e) {
            if(this.touchStatus){
                // A 距离顶部的高度
                // const startY = this.$refs['A'][0].offsetTop
                // console.log(startY)
                if(this.timer){
                    clearTimeout(this.timer)
                }
                this.timer = setTimeout(() =>{
                    const touchY = e.touches[0].clientY - 79
                    // console.log(touchY)
                    const index = Math.floor((touchY - this.startY) / 20)
                    // console.log(index)
                    if(index >= 0 && index < this.letters.length){
                        this.$emit('change', this.letters[index])
                    }
                },16)
            }
        },
        handleTouchEnd () {
            this.touchStatus = false
        }
    }
}
</script>
<style scoped lang="stylus">
@import "~styles/varibles.styl"
.list
    display:flex
    flex-direction:column
    justify-content:center
    position:absolute
    top:1.58rem
    right:0
    width:.4rem
    height: calc(100% - 1.58rem);
    // height:100%
    // background:red
    .item
        line-height:.4rem
        text-align:center
        color:$bgColor
</style>
